import { useStore } from "@/stores";
import service from "./service";

const store = useStore();
console.log(store.ip);

const gaodeKey = '9d1f314389857530a050e49e84ab2355';

export function getIp() {
    return service({
        url: `https://ipinfo.io/json`,
        method: 'GET'
    })
}
/**
 * 根据IP获取位置信息
 * 有次数限制,需要做缓存处理
 * @param {string} ip 需要搜索的IP地址,若用户不填写IP，则取客户http之中的请求来进行定位
 * @returns 
 */
export function getGaodePosition(ip) {
    return service({
        url: `https://restapi.amap.com/v3/ip`,
        method: 'GET',
        params: {
            key: gaodeKey,//高德平台申请的天气预报服务key
            ip: ip
        }
    })
}

/**
 * 根据城市编码查询天气
 * 有次数限制,需要做缓存处理
 * @param {string} adcode 城市编码
 * @param {string} type 气象类型,默认是base,可选值 base(返回实况天气),all(返回预报天气)
 * @returns 
 */
export function geGaodeWeather(adcode, type = 'base') {
    console.log("根据城市编码查询天气");
    return service({
        url: `https://restapi.amap.com/v3/weather/weatherInfo`,
        method: 'GET',
        params: {
            key: gaodeKey,//高德平台申请的天气预报服务key
            city: adcode,//城市编码(adcode)
            extensions: type,//气象类型,可选值  base:返回实况天气  all:返回预报天气
            output: "JSON"
        }
    })
}

export const getWeather = () => {
    return new Promise((resolve, reject) => {
        getIp().then(ipInfo => {
            console.log("获取IP信息", ipInfo);
            const ip = ipInfo.ip;
            if (store['city'] && store['city']['ip'] == ip) {
                console.log("有城市信息并且IP与获取的IP一致");
                geGaodeWeather(store['city']['adcode'], 'all').then(weather => {
                    console.log(weather);
                    if (weather && weather['status'] == 1) {
                        resolve(weather)
                    } else {
                        reject(weather)
                    }
                });
            } else {
                console.log("无城市信息");
                getGaodePosition(ip).then(cityInfo => {
                    console.log(cityInfo);
                    if (cityInfo && cityInfo['status'] == 1) {
                        cityInfo['ip'] = ip;
                        store.setCity(cityInfo);
                        geGaodeWeather(cityInfo['adcode'], 'all').then(weather => {
                            console.log(weather);
                            if (weather && weather['status'] == 1) {
                                resolve(weather)
                            } else {
                                reject(weather)
                            }
                        });
                    } else {
                        console.log("获取城市信息失败");
                    }
                });
            }
        })
    });
}